1630C - Paint the Middle - CodeForces Solution


Array Stack

Please click on ads to support us..

Python Code:

import sys,io,os
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
Y=lambda:map(sub,Z().split())
sub=lambda x:int(x)-1
n=int(Z());a=[*Y()];L=[-1]*n
for i in range(n):L[a[i]]=i
for x in range(n):
    if x!=L[a[x]]:break
s={a[x]};ns=set();r=0
for i in range(x+1,n):
    if s:
        if i==L[a[i]]:
            if a[i]in ns:ns.remove(a[i])
            elif a[i]in s:
                s.remove(a[i])
                if not s:s,ns=ns,set();r-=1
        elif a[i]not in s:ns.add(a[i])
        r+=1
    elif i!=L[a[i]]:s.add(a[i])
print(r)

C++ Code:

#include <algorithm>
#include <deque>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>

using namespace std;

typedef long long ll;
typedef vector<int> veci;
typedef vector<ll> vecll;

long long mod = 998244353;

int main(){
    int n;
    cin >> n;
    vector<int> a(n, 0);
    for(auto& x : a) cin >> x;
   
    map<int, int> l, r;
    for(int i = n - 1; i >= 0; --i){
        if(r.find(a[i]) == r.end()) r[a[i]] = i;
    }

    int m = 0, begin = 0, end, pivot = 1;
    while(begin < n){
        //cerr << "begin : " << begin <<endl;
        end = r[a[begin]];
        ++m;
        //cerr << "increment " << m << endl;
        pivot = max(pivot, begin + 1);
        int new_begin = -1, new_end = -1;
        while(pivot < end){
            if(r[a[pivot]] > end){
                if(r[a[pivot]] > new_end){
                    new_end = r[a[pivot]];
                    new_begin = pivot;
                }
            }
            ++pivot;
        }
        if(new_begin == -1){
            //cerr << "next chunk" << endl;
            if(end > begin) ++m;
            //cerr << "increment " << m << endl;
            begin = end + 1;
        }
        else{
            begin = new_begin;
        }
    }
    cout << n - m << endl;
}


Comments

Submit
0 Comments
More Questions

579A - Raising Bacteria
723A - The New Year Meeting Friends
302A - Eugeny and Array
1638B - Odd Swap Sort
1370C - Number Game
1206B - Make Product Equal One
131A - cAPS lOCK
1635A - Min Or Sum
474A - Keyboard
1343A - Candies
1343C - Alternating Subsequence
1325A - EhAb AnD gCd
746A - Compote
318A - Even Odds
550B - Preparing Olympiad
939B - Hamster Farm
732A - Buy a Shovel
1220C - Substring Game in the Lesson
452A - Eevee
1647B - Madoka and the Elegant Gift
1408A - Circle Coloring
766B - Mahmoud and a Triangle
1618C - Paint the Array
469A - I Wanna Be the Guy
1294A - Collecting Coins
1227A - Math Problem
349A - Cinema Line
47A - Triangular numbers
1516B - AGAGA XOOORRR
1515A - Phoenix and Gold